//
//  CNServiceDataManager.m
//  CarNote
//
//  Created by linshili on 13-9-17.
//  Copyright (c) 2013年 linshili. All rights reserved.
//

#import "CNServiceDataManager.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"

@interface CNServiceDataManager ()

@property (nonatomic, strong) FMDatabaseQueue *fmDatabaseQueue;

@end


@implementation CNServiceDataManager


+ (id)shareInstance
{
    static CNServiceDataManager *serviceDataManager;
    static dispatch_once_t onceTokenCNServiceDataManager;
    dispatch_once(&onceTokenCNServiceDataManager, ^{
        serviceDataManager = [[CNServiceDataManager alloc] init];
    });
    
    return serviceDataManager;
}


- (id)init
{
    self = [super init];
    if (self) {
        //get database file path
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docsPath = [paths objectAtIndex:0];
        NSString *path = nil;
        NSString *userName = nil; // 将来按用户区分
        if (userName != nil) {
            NSString *dbFileName = [[NSString alloc] initWithFormat:@"CarNote.%@.db", userName];
            path = [docsPath stringByAppendingPathComponent:dbFileName];
        }
        else {
            path = [docsPath stringByAppendingPathComponent:@"CarNote.default.db"];
        }
        _fmDatabaseQueue = [FMDatabaseQueue databaseQueueWithPath:path];
    
        [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
            if ([db tableExists:@"ServiceData"] == NO) {
                NSString *createSQL = @"create table ServiceData(createTimestamp int primary key, odometer int, services text, memo text)";
                
                if ([db executeUpdate:createSQL]) {
                    NSLog(@"create table ServiceData succeed");
                }
                else {
                    NSLog(@"create table ServiceData failed");
                }
                
            }
        }];
    }
    
    return self;
}


- (BOOL)saveServiceInfo:(CNServiceInfo *)serviceInfo
{
    __block BOOL res;
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        
        NSString *replaceSQL = [NSString stringWithFormat:@"replace into ServiceData(createTimestamp, odometer, services, memo) \
                                values(?,?,?,?)"];
        
        res = [db executeUpdateWithFormat:replaceSQL,
               [NSNumber numberWithUnsignedInteger:serviceInfo.createTimestamp],
               [NSNumber numberWithInteger:serviceInfo.odometer],
               [serviceInfo jsonStringFromServices],
               serviceInfo.memo];
        
    }];
    
    return res;
    
}


- (NSArray *)queryServiceInfoFromTimestamp:(NSUInteger)fromTimestamp toTimestamp:(NSUInteger)toTimestamp
{
    __block NSMutableArray *serviceInfoArray = [[NSMutableArray alloc] init];
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:@"select createTimestamp, odometer, services, memo \
                                  from ServiceData where createTimestamp >= %u and createTimestamp <= %u", fromTimestamp, toTimestamp];
        
        while ([resultSet next]) {
            CNServiceInfo *serviceInfo = [self rowToServiceInfo:resultSet];
            [serviceInfoArray addObject:serviceInfo];
        }
        
        [resultSet close];
    }];
    
    return serviceInfoArray;
}


- (NSArray *)queryServiceInfoFromIndex:(NSInteger)index withCount:(NSInteger)count
{
    __block NSMutableArray *serviceInfoArray = [[NSMutableArray alloc] init];
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:@"select createTimestamp, odometer, services, memo \
                                  from ServiceData limit %d , offset %d", count, index];
        
        while ([resultSet next]) {
            CNServiceInfo *serviceInfo = [self rowToServiceInfo:resultSet];
            [serviceInfoArray addObject:serviceInfo];
        }
        [resultSet close];
    }];
    
    return serviceInfoArray;

}


- (BOOL)deleteServiceInfoWithTimestamp:(NSUInteger)timestamp
{
    __block BOOL res = NO;
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdateWithFormat:@"delete from ServiceData where createTimestamp = %u", timestamp];
    }];
    
    return res;
}


- (CNServiceInfo *)rowToServiceInfo:(FMResultSet *)resultRet
{
    CNServiceInfo *serviceInfo = [[CNServiceInfo alloc] init];
    serviceInfo.createTimestamp = [resultRet intForColumn:@"createTimestamp"];
    serviceInfo.odometer = [resultRet intForColumn:@"odometer"];
    [serviceInfo servicesFromJsonString:[resultRet stringForColumn:@"services"]];
    serviceInfo.memo = [resultRet stringForColumn:@"memo"];
    
    return serviceInfo;
}

- (NSInteger)serviceInfoCount
{
    __block NSInteger count = 0;
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        count = [db intForQuery:@"select count(*) from ServiceData"];
    }];
    
    return count;
}


@end
